/*
* @Author: Marte
* @Date:   2017-11-28 10:21:40
* @Last Modified by:   Marte
* @Last Modified time: 2017-12-01 17:36:46
*/

(function(){
  m = "test";
  myChart = {};
  hotPoints =[];
  boxPoints =[];
  getBlockInfo();
  createGoEasy();
  createBsTable();
})()
//创建GoEasy
function createGoEasy(){
  var goEasy = new GoEasy({
   appkey: 'BC-6b57efe2846942b2bbbc3726f40b9a14'
 });
  goEasy.subscribe({
    channel: 'data:1',
    onMessage: function(message){
      setBlockNum($.parseJSON(message.content))
    }
  });
}
//获取人流信息
function getBlockInfo(){
  var data;
  var url = "/data/init"
  if(m =="test") url = "init.json"
  $.getJSON(url,{},function(d,c){callback(d,c)})
  function callback(d,c){
    var code = d["code"] || "error !!!!",
    msg = d["msg"];
    data = d["data"];
    console.log("c :"+c);
    console.log("code: "+code);
    console.log("msg :" +msg);
    if(code == 200)
      setBlockNum(data);
  }
}

//更新人流信息
function setBlockNum(config){
  //参数列表
  var cNameList = ["allOnlineCount","last5minCount","topCount"]
  for(var i=0;i<cNameList.length;i++){
    if(cNameList[i] in config){
      var name = cNameList[i];
      var el = $("#"+name);
      if(!el.find(">li").length){
        console.log(el);
        console.log(config[name]);
        el.numberScroll("init",config[name]);
      }else{
        console.log("else");
        el.numberScroll("set",config[name]);
      }
    }
  }
}
//获取本页所有盒子的经纬度
function getBoxPoints(){
  var tb_data = $("#box_tb").bootstrapTable("getData"),
  points = buildPoints(tb_data);
  return points
}
//用表数据生成points
function buildPoints(data){
  var list = [];
  var pointSize = 150;
  for(var i =0;i<data.length;i++){
    var d = data[i]
    if(d.lat && d.lng){
      var lat = parseFloat(d.lat),
          lng = parseFloat(d.lng);
      list.push({name:d.name,value:[lng,lat,pointSize]})
    }
  }
  return list
}
//随机点数，测试用
function randomPoints(p){
  var pp =[],
      x,y;
  for(var i=0;i<1001;i++){
    var f = i%2 == 0?-1:1;
    x=p[0] + Math.random()/10*f;
    y=p[1] + Math.random()/10*f;
    pp.push([x,y])
  }
  return pp;
}
//获取 hot坐标列表
function gethotPoints(){
  var p = [113.103399,23.020271]
  var points = randomPoints(p);
  return points
}
//构建热地图
function buildChart(myChart,hotPoints,boxPoints){
  var p =  [113.103399,23.020271];
  var option = {
      animation:false,
      bmap:{
        center: p,
        zoom: 14,
        roam: true
      },
      tooltip : {
        trigger: 'item'
      },
      visualMap: {
        show: false,
        top: 'top',
        min: 0,
        max: 5,
        seriesIndex: 0,
        calculable: true,
        inRange: {
          color: ['blue', 'blue', 'green', 'yellow', 'red']
        }
      },
      series: [{
        type:'heatmap',
        coordinateSystem: 'bmap',
        data: hotPoints,
        pointSize: 5,
        blurSize: 6
      },{
        name:"盒子",
        type:'effectScatter',
        showEffectOn: 'emphasis',
        rippleEffect: {
          brushType: 'stroke'
        },
        symbolSize: function (val) {
                return val[2] / 10;
            },
        itemStyle: {
                normal: {
                    color: 'green',
                    shadowBlur: 10,
                    shadowColor: '#333'
                }
            },
        coordinateSystem: 'bmap',
        data: boxPoints,
        zlevel: 1
      }
      ]
    };
    myChart.setOption(option)
}
//加载热地图
function loadHeatMap(){
    var dom = document.getElementById("heatmap");
    myChart =  echarts.init(dom),
    hotPoints = gethotPoints(),
    boxPoints = getBoxPoints();
    buildChart(myChart,hotPoints,boxPoints);
}
//重新载入地图上的box
function reloadBoxMap(){
  console.log(myChart);
  boxPoints = getBoxPoints();
  buildChart(myChart,hotPoints,boxPoints);
}
//重新载入地图上的hot点
function reloadheatMap(){
  hotPoints = gethotPoints();
  buildChart(myChart,hotPoints,boxPoints);
}

//创建表
function createBsTable(c){
  if(m != "test"){
    console.log("table produc");
    $('#box_tb').bootstrapTable({
            url: '/boxlist',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            // data:d,
            striped: true,                      //是否显示行间隔色
            pagination: true,                   //是否显示分页（*）
            sortable: false,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: function (params) {
                params.page = params.offset +1;
                return params
            },//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 1,                       //每页的记录行数（*）
            pageList: [5,10,20],        //可供选择的每页的行数（*）
            strictSearch: true,
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
            showToggle:true,                    //是否显示详细视图和列表视图的切换按钮
            // showHeader:false,
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            hideLoading:true,
            search:true,
            responseHandler:function(res){
              var code = res.code,
              msg = res.msg;
              var json = res
              console.log(msg);
              if(code == 200){
                json = {total:res.data.totalCount,rows:res.data.list}
              }
              return json;
            },
            onLoadSuccess:function(){
              $(".fixed-table-header").hide();
              loadHeatMap();
            },
            onLoadError:function(){
              $(".fixed-table-header").hide();
              loadHeatMap();
            },
            onPostBody:function(){
              $(".fixed-table-header").hide();
              loadHeatMap();
            },
            onPageChange:function(e){
              e = e || window.event;
              e.preventDefault();
              e.stopPropagation();
              reloadBoxMap();
            },
            columns: [{
              field: 'macAddr',
              title: '盒子MAC'
            },{
              field: 'name',
              title: '盒子名称'
            }, {
              field: 'lat',
              title: '经度'
            },{
              field: 'lng',
              title: '纬度'
            }, {
              field: 'status',
              title: '状态'
            }, {
              field: 'onlineCount',
              title: '在线人数'
            }, ]
          });
  }else{
    $.getJSON("./box.json",function(d){
      var code = d.code,
          msg = d.msg,
          data = d;
          console.log(msg);
          if(code == 200){
            data = d.data.list;
          }

      $('#box_tb').bootstrapTable({
            data:data,
            striped: true,                      //是否显示行间隔色
            pagination: true,                   //是否显示分页（*）
            sortable: false,                     //是否启用排序
            queryParams: queryParams,//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 1,                       //每页的记录行数（*）
            pageList: [1,2,5,10],        //可供选择的每页的行数（*）
            strictSearch: true,
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
            showToggle:true,                    //是否显示详细视图和列表视图的切换按钮
            // showHeader:false,
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            hideLoading:true,
            search:true,
            onDblClickRow:function(row){

            },
            onLoadSuccess:function(){
              $(".fixed-table-header").hide();
              loadHeatMap();
            },
            onLoadError:function(){
              $(".fixed-table-header").hide();
              loadHeatMap();
            },
            onPostBody:function(){
              $(".fixed-table-header").hide();
              loadHeatMap();
            },
            onPageChange:function(){
              reloadBoxMap();
            },
            columns: [{
              searchable:true,
              field: 'macAddr',
              title: '盒子MAC'
            },{
              searchable:true,
              field: 'name',
              title: '盒子名称'
            }, {
              field: 'lat',
              title: '经度'
            },{
              field: 'lng',
              title: '纬度'
            }, {
              field: 'status',
              title: '状态'
            }, {
              field: 'onlineCount',
              title: '在线人数'
            }, ]
          });
    });
  }
  //得到查询的参数
  var queryParams = function (params) {
      console.log(params);
      params.page = params.offset +1;
      return params
  };
}



